/** 
 * @Title:  LoginController.java 
 * @author:  xuron
 * @data:  2015年11月23日 下午3:14:39 <创建时间>
 * 
 * @history：<以下是历史记录>
 *
 * @modifier: <修改人>
 * @modify date: 2015年11月23日 下午3:14:39 <修改时间>
 * @log: <修改内容>
 *
 * @modifier: <修改人>
 * @modify date: 2015年11月23日 下午3:14:39 <修改时间>
 * @log: <修改内容>
 */
package com.woyou.controller;

import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import com.jing.biandang.R;
import com.woyou.Constants;
import com.woyou.WoYouApplication;
import com.woyou.activity.HomeActivity;
import com.woyou.activity.LoginActivity;
import com.woyou.bean.DeliveryTime;
import com.woyou.bean.UserInfo;
import com.woyou.bean.WYList;
import com.woyou.bean.rpc.QueryVerificationCodeReq;
import com.woyou.bean.rpc.Result;
import com.woyou.bean.rpc.ServerTimeRes;
import com.woyou.bean.rpc.UpdateVersionReq;
import com.woyou.bean.rpc.UpdateVersionRes;
import com.woyou.bean.rpc.UserLoginReq;
import com.woyou.bean.rpc.UserLoginRes;
import com.woyou.component.SuperUI;
import com.woyou.model.rpc.ShopModel;
import com.woyou.model.rpc.UserModel;
import com.woyou.utils.DownloadeManager;
import com.woyou.utils.FormatTools;
import com.woyou.utils.LoginUtils;
import com.woyou.utils.MainBoardUtil;
import com.woyou.utils.StateJudgeTools;
import com.woyou.utils.ThreadPoolManager;
import com.woyou.utils.TypeJudgeTools;
import com.woyou.utils.Utils;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import retrofit.RetrofitError;

/**
 * 抽取LoginActivity的逻辑
 * 
 * @author xuron
 * @versionCode 1 <每次修改提交前+1>
 */
public class LoginController extends SuperController {
	/**
	 * 输入法控制器
	 */
	private InputMethodManager imm;
	/**
	 * 登陆
	 */
	private LoginActivity loginActivity;
	/**
	 * 旋转动画
	 */
	private RotateAnimation rotateAnimation;
	/**
	 * 判断是否运行中isRunning
	 */
	private boolean isRunning = true;
	/**
	 * 同步服务器时间
	 */
	private String sTime = "";
	private Result<ServerTimeRes> serverTime;
	/**
	 * 自动登录的计时器
	 */
	private Timer timer;
	private TimerTask timerTask;
	/**
	 * 是否取消更新超时倒计时
	 */
	private boolean isUpdateTimeout = true;
	/**
	 * 是否自动登陆
	 */
	private boolean isAutoLogin = true;
	/**
	 * 密码错误重试次数
	 */
	private int timesNum = 0;
	/**
	 * 自动登录
	 */
	private UserInfo autoUserInfo;
	private UserLoginReq autoUserLoginReq;
	private UserLoginRes autoUserLoginRes;
	private Result<UserLoginRes> autoResult;
	/**
	 * 更新信息
	 */
	private Result<UpdateVersionRes> updateVersionResult;
	/**
	 * 更新对话框
	 */
	private Dialog updateDialog;
	/**
	 * 更新超时倒计时
	 */
	private int updateTimeOut = 0;
	private String id;
	private String uname;
	private String code;
	// 刚开机初始化，deviceCode和versionCode可能获取不到
	private String deviceCode;
	private String versionCode;
	private int loginType;
	private String pwd;
	// 手动登录
	private UserLoginReq userLoginReq;
	private UserLoginRes userLoginRes;
	private Result<UserLoginRes> result;
	
	/**
	 * @param mContext
	 */
	public LoginController(Context mContext) {
		super(mContext);
		this.mContext = mContext;
		loginActivity = (LoginActivity) mContext;
		imm = (InputMethodManager) loginActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
	}

	/**
	 * 手动登录操作
	 */
	public void login(final EditText login_id_et,final EditText login_uname_et,final EditText login_code_et,final ImageView loading_iv,final RelativeLayout loading_hint) {
		id = login_id_et.getText().toString();
		uname = login_uname_et.getText().toString();
		code = login_code_et.getText().toString();
		pwd = producePwd();
		loginType = 0;
		if (TypeJudgeTools.isNull(id)) {
			SuperUI.openToast(mContext, "请输入店铺ID");
		} else if (TypeJudgeTools.isNull(uname)) {
			SuperUI.openToast(mContext, "请输入用户名");
		} else if (TypeJudgeTools.isNull(code)) {
			SuperUI.openToast(mContext, "请输入验证码");
		} else {
			// 登录
			executeTask(new Runnable() {
				@Override
				public void run() {
					try {
						if (!syncServerTime(loading_hint)) {
							return;
						}
						id = login_id_et.getText().toString();
						uname = login_uname_et.getText().toString();
						code = login_code_et.getText().toString();
						deviceCode = Utils.getDeviceCode(mContext);
						versionCode = "" + Utils.getVersionCode(mContext);
						if (!TypeJudgeTools.isNull(deviceCode) && !TypeJudgeTools.isNull(versionCode)) {
							stopAutoLogin();
							showLoadingHint(loading_hint, loading_iv);
							userLoginReq = new UserLoginReq();
							userLoginReq.setbId(id);
							userLoginReq.setuCode(uname);
							userLoginReq.setCode(code);
							userLoginReq.setPwd(pwd);
							userLoginReq.setLoginType(loginType);
							userLoginReq.setDeviceId(deviceCode);
							userLoginReq.setVersion(versionCode);
							result = UserModel.getInstance(mContext).v2_3userLogin(userLoginReq);
							hideLoadingHint(loading_hint);
							if (result != null && result.code == 1) {
								userLoginRes = result.getData();
								if (userLoginRes != null && userLoginRes.getsId() != null) {
									// 存储用户登录信息
									aCache.put("loginUserInfo", userLoginRes);
									UserInfo userInfo = new UserInfo();
									userInfo.setbId(userLoginReq.getbId());
									userInfo.setsId(userLoginRes.getsId());
									userInfo.setuCode(userLoginReq.getuCode());
									userInfo.setsName(userLoginRes.getsName());
									userInfo.setCode(userLoginReq.getCode());
									userInfo.setPwd(userLoginReq.getPwd());
									userInfo.setLoginType(userLoginReq.getLoginType());
									userInfo.setDeviceId(userLoginReq.getDeviceId());
									userInfo.setVersion(WoYouApplication.VersionCode + "");
									userInfo.setServerIP(userLoginRes.getServerIP());
									userInfo.setServerPort(userLoginRes.getServerPort());

									// 存储外卖时间段
									List<DeliveryTime> deliveryList = userLoginRes.getDeliveryTimeList();
									if (deliveryList != null) {
										WYList<DeliveryTime> deliveryWyList = new WYList<DeliveryTime>();
										deliveryWyList.addAll(deliveryList);
										aCache.put("delivertime", deliveryWyList);
									}
									// 将用户登录信息写入sp
									LoginUtils.saveUserInfo(userInfo,mContext);
									// 将用户登录信息写入TF卡
									Utils.writeUserInfo2TF(userInfo);
									// 默认设置营业中
									Constants.shopStatus = "S";
									// 设置店铺id
									Constants.shopCode = userLoginRes.getsId();
									// 设置店铺名
									Constants.shopName = userLoginRes.getsName();

									Constants.HEART_BEAT_SERVER = userLoginRes.getServerIP();
									if (!TypeJudgeTools.isNull(userLoginRes.getServerPort())) {
										Constants.HEART_BEAT_SERVER_PORT = Integer.valueOf(userLoginRes.getServerPort());
									}
									// 检测更新
									checkUpdate(loading_iv, loading_hint);
								}
							} else if (result != null && (result.code == -1 || result.getCode() == -2)) {
								runOnUI(new Runnable() {
									public void run() {
										SuperUI.openToast(mContext, result.msg);
									}
								});
								startAutoLogin(loading_iv, loading_hint);
							} else if (result != null && result.code == -3) {
								runOnUI(new Runnable() {
									public void run() {
										SuperUI.openToast(mContext, result.msg);
									}
								});
								startAutoLogin(loading_iv, loading_hint);
							} else {
								startAutoLogin(loading_iv, loading_hint);
							}
						}
					} catch (RetrofitError error) {
						hideLoadingHint(loading_hint);
						startAutoLogin(loading_iv, loading_hint);
						switch (error.getKind()) {
						case CONVERSION:
						case HTTP:
							runOnUI(new Runnable() {
								public void run() {
									SuperUI.openToast(mContext, "服务器又任性了！");
								}
							});
							break;
						case NETWORK:
							runOnUI(new Runnable() {
								public void run() {
									SuperUI.openToast(mContext, "请检查网络连接！");
								}
							});
							break;
						case UNEXPECTED:
							runOnUI(new Runnable() {
								public void run() {
									SuperUI.openToast(mContext, "未知错误！");
								}
							});
							break;
						}
					}
				}
			});
		}
	}
	/**
	 * 获取验证码
	 */
	public void getCode(final RelativeLayout loading_hint,final ImageView loading_iv,TextView login_nettype,EditText login_id_et,EditText login_uname_et) {
		if (!login_nettype.getText().toString().equals("无网络")) {
			id = login_id_et.getText().toString();
			uname = login_uname_et.getText().toString();
			if (TypeJudgeTools.isNull(id)) {
				SuperUI.openToast(mContext, "请输入店铺ID");
			} else if (TypeJudgeTools.isNull(uname)) {
				SuperUI.openToast(mContext, "请输入用户名");
			} else {
				ThreadPoolManager.getInstance().executeTask(new Runnable() {
					@Override
					public void run() {
						try {
							showLoadingHint(loading_hint,loading_iv);
							QueryVerificationCodeReq queryVCodeReq = new QueryVerificationCodeReq();
							queryVCodeReq.setbId(id);
							queryVCodeReq.setuCode(uname);
							final Result result = UserModel.getInstance(mContext).queryVerificationCode(queryVCodeReq);
							runOnUI(new Runnable() {
								@Override
								public void run() {
									if (result != null) {
										if (result.code == 1) {
											SuperUI.openToast(mContext,result.msg);
										} else {
											SuperUI.openToast(mContext,result.msg);
										}
									} else {
										SuperUI.openToast(mContext,"网络连接错误！");
									}
								}
							});
						} catch (RetrofitError error) {
							switch (error.getKind()) {
							case CONVERSION:
								runOnUI(new Runnable() {
									public void run() {
										SuperUI.openToast(mContext,"服务器又任性了！");
									}
								});
								break;
							case HTTP:
								runOnUI(new Runnable() {
									public void run() {
										SuperUI.openToast(mContext,"服务器又任性了！");
									}
								});
								break;
							case NETWORK:
								runOnUI(new Runnable() {
									public void run() {
										SuperUI.openToast(mContext,"请检查网络连接！");
									}
								});
								break;
							case UNEXPECTED:
								runOnUI(new Runnable() {
									public void run() {
										SuperUI.openToast(mContext,"请检查网络连接！");
									}
								});
								break;
							}
						} finally {
							hideLoadingHint(loading_hint);
						}
					}
				});
			}
		} else {
			SuperUI.openToast(mContext, "请检查网络连接！");
		}
	}
	/**
	 * 设置密码
	 * 
	 * @return
	 */
	public String producePwd() {
		Random random = new Random();
		int num = 0;
		while (true) {
			num = (int) (random.nextDouble() * (1000000 - 100000) + 100000);
			if (!(num + "").contains("4"))
				break;
		}
		return String.valueOf(num);
	}

	/**
	 * 提示更新的dialog
	 * 
	 * @param isForce
	 *            是否强制更新
	 * @param context
	 * @param updateInfo3
	 */
	public void openUpdateDialog(boolean isForce, final Context context, final UpdateVersionRes updateVersionRes) {
		if (updateDialog == null) {
			updateDialog = new Dialog(context, R.style.defaultDialogStyle);
		} else if (updateDialog.isShowing()) {
			return;
		}
		View view = LayoutInflater.from(context).inflate(R.layout.layout_checkupdate, null);
		TextView checkupdate_info = (TextView) view.findViewById(R.id.layout_checkupdate_info);
		RelativeLayout checkupdate_cancel = (RelativeLayout) view.findViewById(R.id.layout_checkupdate_cancel);
		final TextView layout_checkupdate_cancel_tv = (TextView) view.findViewById(R.id.layout_checkupdate_cancel_tv);
		RelativeLayout checkupdate_down = (RelativeLayout) view.findViewById(R.id.layout_checkupdate_down);
		// 根据标志位判断是否显示取消更新按钮
		if (isForce) {
			checkupdate_cancel.setVisibility(View.GONE);
		} else {
			checkupdate_cancel.setVisibility(View.VISIBLE);
		}
		updateDialog.setContentView(view);
		updateDialog.setCanceledOnTouchOutside(false);
		updateDialog.show();
		checkupdate_info.setText(updateVersionRes.getInfo().replace("<LF>", "\n"));
		checkupdate_cancel.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) {
				isUpdateTimeout = false;
				updateDialog.dismiss();
				jump2Home();
			}
		});
		checkupdate_down.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) {
				isUpdateTimeout = false;
				updateDialog.dismiss();
				new DownloadeManager(loginActivity, "" + updateVersionRes.getUpdateUrl())
						.showDownloadDialog(loginActivity, true);
			}
		});
		// 等待更新超时
		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					updateTimeOut = 60;
					while (isUpdateTimeout) {
						runOnUI(new Runnable() {
							public void run() {
								if (updateTimeOut == 1) {
									isUpdateTimeout = false;
									updateDialog.dismiss();
									jump2Home();
								}
								layout_checkupdate_cancel_tv.setText("以后再说(" + (updateTimeOut--) + ")");
							}
						});
						// 延迟1s
						Thread.sleep(1000);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 检测软件更新
	 */
	public void checkUpdate(final ImageView loading_iv, final RelativeLayout loading_hint) {
		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					showLoadingHint(loading_hint, loading_iv);
					UpdateVersionReq updateVersionReq = new UpdateVersionReq();
					updateVersionReq.setAppName("BD_VERSION2");
					updateVersionReq.setBoardType(MainBoardUtil.getModel());
					updateVersionReq.setPwd(LoginUtils.getUserInfo(mContext).getPwd());
					updateVersionReq.setsId(LoginUtils.getUserInfo(mContext).getsId());
					updateVersionReq.setVersion(LoginUtils.getUserInfo(mContext).getVersion());
					updateVersionResult = UserModel.getInstance(mContext).updateVersion(updateVersionReq);
					runOnUI(new Runnable() {
						@Override
						public void run() {
							if (updateVersionResult != null && updateVersionResult.code == 1) {
								UpdateVersionRes updateVersionRes = updateVersionResult.getData();
								if (updateVersionRes != null && updateVersionRes.getIsUpdate() == 1) {
									if (updateVersionRes.getType() == 1) {
										// 强制更新
										openUpdateDialog(true, mContext, updateVersionRes);
									} else {
										// 选择更新
										openUpdateDialog(false, mContext, updateVersionRes);
									}
								} else {
									jump2Home();
								}
							} else if (updateVersionResult != null && updateVersionResult.code == -3) {
								runOnUI(new Runnable() {
									@Override
									public void run() {
										SuperUI.openToast(mContext, "您的账号已在其他地方登陆，请您重新登录！");
									}
								});
							} else {
								jump2Home();
							}
						}
					});
				} catch (RetrofitError error) {
					switch (error.getKind()) {
					case CONVERSION:
						runOnUI(new Runnable() {
							public void run() {
								SuperUI.openToast(mContext, "服务器又任性了！");
							}
						});
						break;
					case HTTP:
						runOnUI(new Runnable() {
							public void run() {
								SuperUI.openToast(mContext, "服务器又任性了！");
							}
						});
						break;
					case NETWORK:
						runOnUI(new Runnable() {
							public void run() {
								SuperUI.openToast(mContext, "请检查网络连接！");
							}
						});
						break;
					case UNEXPECTED:
						runOnUI(new Runnable() {
							public void run() {
								SuperUI.openToast(mContext, "请检查网络连接！");
							}
						});
						break;

					default:
						break;
					}
				} finally {
					hideLoadingHint(loading_hint);
				}
			}
		});
	}

	/**
	 * 自动登录
	 */
	public void autoLogin(final ImageView loading_iv, final RelativeLayout loading_hint) {
		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					if (!syncServerTime(loading_hint)) {
						try {
							Thread.sleep(2000);
						} catch (Exception ee) {
						}
						if (!isAutoLogin) {
							return;
						}
						autoLogin(loading_iv, loading_hint);
						return;
					}
					autoUserInfo = LoginUtils.getUserInfo(mContext);
					if (autoUserInfo != null && autoUserInfo.getbId().equals("")) {
						// 读取TF卡中的用户信息
						autoUserInfo = Utils.readUserInfo4TF();
					}
					if (autoUserInfo != null && !TextUtils.isEmpty(autoUserInfo.getuCode())
							&& !TextUtils.isEmpty(autoUserInfo.getbId())) {
						autoUserLoginReq = new UserLoginReq();
						autoUserLoginReq.setbId(autoUserInfo.getbId());
						autoUserLoginReq.setuCode(autoUserInfo.getuCode());
						autoUserLoginReq.setCode(autoUserInfo.getCode());
						autoUserLoginReq.setPwd(autoUserInfo.getPwd());
						autoUserLoginReq.setLoginType(1);
						autoUserLoginReq.setDeviceId(Utils.getDeviceCode(mContext));
						autoUserLoginReq.setVersion("" + Utils.getVersionCode(mContext));
						autoResult = UserModel.getInstance(mContext).v2_3userLogin(autoUserLoginReq);
						if (autoResult != null && autoResult.code == 1) {
							stopAutoLogin();
							autoUserLoginRes = autoResult.getData();
							if (autoUserLoginRes != null && autoUserLoginRes.getsId() != null) {
								// 存储用户登录信息
								aCache.put("loginUserInfo", autoUserLoginRes);
								UserInfo autoUserInfo = new UserInfo();
								autoUserInfo.setbId(autoUserLoginReq.getbId());
								autoUserInfo.setsId(autoUserLoginRes.getsId());
								autoUserInfo.setuCode(autoUserLoginReq.getuCode());
								autoUserInfo.setsName(autoUserLoginRes.getsName());
								autoUserInfo.setCode(autoUserLoginReq.getCode());
								autoUserInfo.setPwd(autoUserLoginReq.getPwd());
								autoUserInfo.setLoginType(autoUserLoginReq.getLoginType());
								autoUserInfo.setDeviceId(Utils.getDeviceCode(mContext));
								autoUserInfo.setVersion("" + Utils.getVersionCode(mContext));
								autoUserInfo.setServerIP(autoUserLoginRes.getServerIP());
								autoUserInfo.setServerPort(autoUserLoginRes.getServerPort());

								// 存储外卖时间段
								List<DeliveryTime> deliveryList = autoUserLoginRes.getDeliveryTimeList();
								if (deliveryList != null) {
									WYList<DeliveryTime> deliveryWyList = new WYList<DeliveryTime>();
									deliveryWyList.addAll(deliveryList);
									aCache.put("delivertime", deliveryWyList);
								}
								// 将用户登录信息写入sp
								LoginUtils.saveUserInfo(autoUserInfo, mContext);
								// 将用户登录信息写入TF卡
								Utils.writeUserInfo2TF(autoUserInfo);
								// 默认设置营业中
								Constants.shopStatus = "S";
								// 设置店铺id
								Constants.shopCode = autoUserLoginRes.getsId();
								// 设置店铺名
								Constants.shopName = autoUserLoginRes.getsName();
								Constants.HEART_BEAT_SERVER = autoUserLoginRes.getServerIP();
								if (!TypeJudgeTools.isNull(autoUserLoginRes.getServerPort())) {
									Constants.HEART_BEAT_SERVER_PORT = Integer
											.valueOf(autoUserLoginRes.getServerPort());
								}
								// 检测更新
								checkUpdate(loading_iv, loading_hint);
							}
						} else if (autoResult != null && autoResult.code == -3) {
							runOnUI(new Runnable() {
								public void run() {
									SuperUI.openToast(mContext, autoResult.msg);
								}
							});
							timesNum = timesNum + 1;
							if (timesNum >= 10) {
								stopAutoLogin();
							}
						}
					}

				} catch (RetrofitError error) {
				}

			}
		});

	}

	/**
	 * 自动登录成功跳转到home页面
	 */
	public void jump2Home() {
		// 取消自动登录
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		if (timerTask != null) {
			timerTask.cancel();
			timerTask = null;
		}

		Intent intent = new Intent(mContext, HomeActivity.class);
		mActivity.startActivity(intent);
		mActivity.finish();
	}

	/**
	 * 自动登录
	 */
	public void startAutoLogin(final ImageView loading_iv, final RelativeLayout loading_hint) {
		stopAutoLogin();
		/**
		 * 初始化自动登录计时器
		 */
		timer = new Timer();
		timerTask = new TimerTask() {
			@Override
			public void run() {
				if (timesNum >= 10) {
					return;
				}
				autoLogin(loading_iv, loading_hint);
			}
		};
		// 10s后执行
		timer.schedule(timerTask, 0, 10 * 1000);
	}

	/**
	 * 关闭自动登录
	 */
	public void stopAutoLogin() {
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		if (timerTask != null) {
			timerTask.cancel();
			timerTask = null;
		}
	}

	/**
	 * 销毁
	 */
	public void onDestroy() {
		isAutoLogin = false;
		isRunning = false;
		isUpdateTimeout = false;
		// 关闭自动登录timer、timertask
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		if (timerTask != null) {
			timerTask.cancel();
			timerTask = null;
		}
	}

	/**
	 * 获取网络类型和服务器时间 -1：没有网络 1：WIFI网络 2：wap网络 3：net网络
	 */
	public void getNetTypeAndTime(final TextView login_time, final TextView login_nettype,final ImageView login_neticon) {
		// 更新时间
		executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					while (isRunning) {
						// 判断网络类型
						runOnUI(new Runnable() {
							public void run() {
								int netType = StateJudgeTools.getNetworkState(mContext);
								switch (netType) {
								case 1:
									login_nettype.setText("Wifi");
									login_neticon.setImageResource(R.raw.icon_net_wifi_28);
									break;
								case 3:
									login_nettype.setText("3G");
									login_neticon.setImageResource(R.raw.icon_net_3g_28);
									break;
								case 5:
									login_nettype.setText("有线网络");
									login_neticon.setImageResource(R.raw.icon_net_line_28);
									break;
								default:
									login_nettype.setText("无网络");
									login_neticon.setImageResource(R.raw.icon_net_no_28);
									break;
								}
							}
						});
						// 获取服务器时间
						if (serverTime == null || serverTime != null && serverTime.getData() == null) {
							serverTime = ShopModel.getInstance(mContext).queryServerTime();
							if (serverTime != null && serverTime.getData() != null) {
								sTime = serverTime.getData().getsTime() * 1000 + "";
							}
						}
						runOnUI(new Runnable() {
							public void run() {
								if (!TypeJudgeTools.isNull(sTime)) {
									long time = Long.valueOf(sTime);
									login_time.setText(FormatTools.convertTime(time, "HH:mm"));
									// 10s刷新一次
									sTime = time + 10000 + "";
								}
							}
						});
						// //10s刷新一次
						Thread.sleep(10 * 1000);
					}
				} catch (Exception e) {
					e.printStackTrace();
					try {
						// //10s刷新一次
						Thread.sleep(10 * 1000);
					} catch (Exception exception) {
					}
					getNetTypeAndTime(login_time, login_nettype, login_neticon);
				}
			}
		});
	}

	/**
	 * 同步服务器时间 成功返回true ,失败返回false
	 * 
	 * @return
	 */
	public boolean syncServerTime(RelativeLayout loading_hint) {
		// 尝试3次获取服务器时间
		try {
			for (int i = 0; i < 3; i++) {
				Result<ServerTimeRes> result = ShopModel.getInstance(mContext).queryServerTime();
				if (result != null && result.getCode() == 1 && result.getData() != null) {
					// 储存服务器时间到aCache中
					aCache.put("ServerTime", result.getData().getsTime() * 1000 + "");
					hideLoadingHint(loading_hint);
					return true;
				}
			}
		} catch (Exception e) {
		} finally {
			hideLoadingHint(loading_hint);
		}
		return false;
	}

	/**
	 * 启动图片旋转动画
	 */
	private void startAnim(ImageView layout_loadding_iv) {

		if (rotateAnimation == null) {
			rotateAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
					0.5f);
		}
		rotateAnimation.setDuration(1000);
		rotateAnimation.setInterpolator(new LinearInterpolator());
		rotateAnimation.setRepeatCount(-1);
		layout_loadding_iv.startAnimation(rotateAnimation);
	}

	/**
	 * 关闭图片旋转动画
	 */
	private void stopAnim() {
		if (rotateAnimation != null) {
			rotateAnimation.cancel();
		}
	}

	/**
	 * 显示隐藏载入View
	 */
	public void showLoadingHint(final RelativeLayout loading_hint, final ImageView loading_iv) {
		runOnUI(new Runnable() {
			@Override
			public void run() {
				startAnim(loading_iv);
				loading_hint.setVisibility(View.VISIBLE);
			}
		});
	}

	/**
	 * 隐藏数据载入View
	 */
	public void hideLoadingHint(final RelativeLayout loading_hint) {
		runOnUI(new Runnable() {
			@Override
			public void run() {
				stopAnim();
				loading_hint.setVisibility(View.GONE);
			}
		});

	}

	/**
	 * 隐藏输入法
	 */
	public void hideSoftInput() {
		imm.hideSoftInputFromWindow(loginActivity.getCurrentFocus().getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
	}

	/**
	 * 防止暴力点击
	 * 
	 * @return
	 */
	public void avoidForceClick(final View v) {
		v.setEnabled(false);
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				v.setEnabled(true);
			}
		}, 2000);
	}
}
